import React, { PureComponent, Fragment, useState } from "react";
import { connect } from "dva";
import moment from "moment";
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tabs,
  Tag,
  Tree,
} from "antd";
import StandardTable from "@/components/StandardTable";
import MyIcon from "@/components/MyIcon";
import IconButton from "@/components/IconButton";
import RoleTree from "./RoleTree";
import Add from "./Add/Add";
import get from "lodash/get";

import styles from "./Content.less";
import Link from "umi/link";
import { stringify } from "querystring";
import { SERVICE_STATUS } from "@/Constants";

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const { TabPane } = Tabs;
const { TreeNode } = Tree;
var platformid = 5;
var parentUserId = 0;

@connect(({ base, product, loading, role }) => ({
  loadingRoleUserList: loading.effects["role/queryMembersByRole"],
  roleUserList: role.roleUserList,
  resultList: role.resultList,
  // orgList: role.orgList,
  checkedKeys: role.checkedTreeNode,
  roleList: role.roleList,
  // orgTree: role.orgTree,
  // groupList: role.groupList,
  deleteLoading: loading.effects["role/deleteMembers"],
  updateRoleTreeLoading: loading.effects["role/updateRoleTree"],
  roleIdss: role.roleIdss,
  newroleIdss: role.newroleIdss,
  userIdss: role.userIdss,
  direction: role.direction,
  checkedList: role.checkedList,
  newCheck: role.newCheck,
  editOrgTreeList: role.editOrgTreeList,
}))
@Form.create()
class Content extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    selectedRows: [],
    currentStatus: "1",
    addType: "1",
    checkedOrgKeys: [],
    checkedGroupKeys: [],
    targetUserKeys: [],
    activeKey: "1",
    // editOrgTreeList: [],
    // checkedList: [],
    pageIndex: "",
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.currentRoleId !== nextProps.currentRoleId) {
      this.setState({
        selectedRows: [],
      });
    }
  }

  memberTypeList = [
    {
      type: "USER",
      name: "用户",
      iconType: "iconoss---yonghu",
      render: (text, record, index) => {
        return <span>修改分组</span>;
      },
    },
    // {
    //   type: 'GROUP',
    //   name: '用户组',
    //   iconType: 'iconoss---yonghuzu',
    //   render: (text, record, index) => {
    //     return <span>用户组</span>;
    //   },
    // },
    // {
    //   type: 'ORG',
    //   name: '组织',
    //   iconType: 'iconoss---zuzhi',
    //   render: (text, record, index) => {
    //     return <span>组&#12288;织</span>;
    //   },
    // },
  ];

  columns = [
    {
      title: "序号",
      // width: '150px',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: "账号",
      dataIndex: "shortName",
      render: (text, record, index) => {
        return (
          <span>
            <MyIcon
              className={styles.myIcon}
              // type={this.memberTypeList.find(member => member.type === record.type).iconType}
            />
            {record.type === "USER"
              ? `${record.shortName}(${record.code})`
              : record.shortName}
            {record.username}
          </span>
        );
      },
    },
    {
      title: "姓名",
      // width: '150px',
      dataIndex: "Name",
      render: (text, record, index) => {
        return <span>{record.name}</span>;
      },
    },
    {
      title: "手机",
      // width: '150px',
      dataIndex: "phone",
      render: (text, record, index) => {
        return <span>{record.mobile}</span>;
      },
    },
    {
      title: "邮箱",
      // width: '150px',
      dataIndex: "email",
      render: (text, record, index) => {
        return <span>{record.email}</span>;
      },
    },
    {
      title: "状态",
      // width: '150px',
      dataIndex: "status",
      render: (text, record, index) => {
        return <span>{record.status}</span>;
      },
    },
  ];

  calcIndex = (index) => {
    const { roleUserList } = this.props;
    let currentPage = get(roleUserList, "pagination.currentPage") || 1;
    let pageSize = get(roleUserList, "pagination.pageSize") || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  searchRoleMembers = ({
    pageIndex = 1,
    pageSize = 50,
    status = this.state.currentStatus,
    ...rest
  } = {}) => {
    const { dispatch, form, currentRoleId } = this.props;
    let queryParams = {
      pageIndex,
      pageSize,
      status,
      ...rest,
    };
    dispatch({
      type: "role/queryMembersByRole",
      payload: {
        // pathParams: {
        //   roleId: currentRoleId,
        // },
        // queryParams: queryParams,
        data: {
          platform: platformid,
          roleId: currentRoleId,
          parentUserId: parentUserId,
        },
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.searchRoleMembers(params);
    this.setState({
      selectedRows: [],
    });
  };

  changePage = (page) => {
    this.setState({
      pageIndex: page,
    });
  };

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  };

  deleteMembers = () => {
    const { dispatch, currentRoleId, deleteLoading } = this.props;
    if (deleteLoading) return;
    const { selectedRows } = this.state;
    console.log(selectedRows);
    const kkk = selectedRows.map((item) => item.userId);
    console.log(kkk);
    Modal.confirm({
      title: "删除",
      content: `确定删除所选成员吗？`,
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        return dispatch({
          type: "role/deleteMembers",
          payload: {
            // pathParams: {
            //   roleId: currentRoleId,
            // },
            // data: selectedRows,
            data: {
              parentUserId: parentUserId,
              platform: platformid,
              userIds: kkk.join(","),
            },
          },
        }).then((res) => {
          if (res.code === 200) {
            message.success("删除成功");
            this.setState({
              selectedRows: [],
            });
            this.searchRoleMembers();
          }
        });
      },
    });
  };

  handleChangeTab = (key) => {
    const { form, currentRoleId } = this.props;
    this.setState({
      // currentStatus: key,
      activeKey: key,
    });
    form.resetFields();
    // key === "1"
    //   ? this.searchRoleMembers({ status: key })
    //   : this.editOrgTree(currentRoleId);
  };

  okHandle = async () => {
    const { dispatch, roleIdss, newroleIdss, userIdss } = this.props;

    this.handleModalVisible();

    var hh = [];
    if (this.props.direction == "right") {
      for (var i = 0; i < userIdss.length; i++) {
        var data = {
          orgRoleId: newroleIdss,
          roleId: +roleIdss,
          userId: userIdss[i],
        };
        console.log(data);
        hh.push(data);
      }
    } else {
      for (var i = 0; i < userIdss.length; i++) {
        var data = {
          orgRoleId: +roleIdss,
          roleId: newroleIdss,
          userId: userIdss[i],
        };
        console.log(data);
        hh.push(data);
      }
    }
    console.log(hh);

    const res = await dispatch({
      type: "role/updateRoleUsers",
      payload: {
        data: {
          platform: platformid,
          // updateSysRoleAndUserList: [
          //   {
          //     orgRoleId: roleIdss,
          //     roleId: newroleIdss,
          //     userId: userIdss,
          //   },
          // ],
          updateSysRoleAndUserList: hh,
        },
      },
    });

    if (res.code === 200) {
      message.success("操作成功");
      this.searchRoleMembers();
      this.handleModalVisible();
      // history.go(0);
    }
  };

  handleModalVisible = () => {
    this.setState({
      modalVisible: false,
    });
  };

  // editOrgTree = (roleId) => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: "role/editOrgTree",
  //     payload: {
  //       data: {
  //         roleId,
  //         parentUserId: parentUserId,
  //         platform: platformid,
  //       },
  //     },
  //   }).then((res) => {
  //     console.log(res);
  //     const { data } = res;

  //     // 转化复选框选中的值
  //     let arr = [];
  //     function a(data) {
  //       data.find((item) => {
  //         if (item.children.length === 0) {
  //           arr.push(item);
  //         }
  //         if (item.children.length > 0) {
  //           a(item.children);
  //         }
  //       });
  //       return arr;
  //     }
  //     let newArr = a(data);
  //     console.log(newArr);
  //     var hello = newArr.map((item) => item.menuId);
  //     console.log(hello);

  //     this.setState({
  //       editOrgTreeList: data,
  //     });
  //     dispatch({
  //       type: "role/newcheckedList",
  //       payload: {
  //         id: hello,
  //       },
  //     });
  //     console.log(this.props.checkedList);
  //   });
  // };

  handleTreeCheck = (checkedKeys) => {
    const { currentRoleId, dispatch } = this.props;
    dispatch({
      type: "role/saveCheckedTreeNode",
      payload: checkedKeys,
    });
  };

  updateTreeNode = () => {
    const {
      checkedKeys,
      currentRoleId,
      dispatch,
      updateRoleTreeLoading,
    } = this.props;
    if (updateRoleTreeLoading) return;
    dispatch({
      type: "role/updateRoleTree",
      payload: {
        data: {
          menuIds: this.props.newCheck,
          platform: platformid,
          roleId: this.props.roleIdss,
        },
      },
    }).then((res) => {
      console.log(res);
      res.code === 200 && message.success("保存成功");
      window.location.reload();
    });
  };

  // queryOrgTree = () => {
  //   const { dispatch, currentRoleId } = this.props;
  //   return dispatch({
  //     type: "role/queryOrgTree",
  //     payload: {
  //       pathParams: {
  //         roleId: currentRoleId,
  //       },
  //     },
  //   });
  // };

  // queryGroupList = () => {
  //   const { dispatch, currentRoleId } = this.props;
  //   return dispatch({
  //     type: 'role/queryGroupList',
  //     payload: {
  //       pathParams: {
  //         roleId: currentRoleId,
  //       },
  //     },
  //   });
  // };

  // getCheckedKeys = (orgList = []) => {
  //   let checkedOrgKeys = [];
  //   function loop(orgList) {
  //     orgList.forEach(node => {
  //       node.selected && checkedOrgKeys.push(node.id);
  //       node.children && loop(node.children);
  //     });
  //   }

  //   loop(orgList);
  //   return checkedOrgKeys;
  // };

  getCheckedGroupKeys = (groupList = []) => {
    let checkboxList = [];
    groupList &&
      groupList.forEach((group) => {
        if (group.selected) {
          checkboxList.push(group.id);
        }
      });
    return checkboxList;
  };
  handleMenuClick = async (e) => {
    this.setState({
      modalVisible: true,
      addType: e.key,
    });

    if (e.key === "1") {
      // this.queryOrgTree();
      this.setState({
        targetUserKeys: [],
      });
      // } else if (e.key === '2') {
      //   await this.queryGroupList();
      //   const checkedGroupKeys = this.getCheckedGroupKeys(this.props.groupList);
      //   this.setState({
      //     checkedGroupKeys,
      //   });
      // } else if (e.key === '2') {
      //   await this.queryOrgTree();
      //   const checkedOrgKeys = this.getCheckedKeys(this.props.orgTree);
      //   this.setState({
      //     checkedOrgKeys,
      //   });
    }
    this.searchRoleMembers();
  };

  handleOrgTreeChcek = (checkedKeys, e) => {
    this.setState({
      checkedOrgKeys: checkedKeys,
    });
  };

  handleGroupCheck = (checkedKeys) => {
    this.setState({
      checkedGroupKeys: checkedKeys,
    });
  };

  handleTargetKeysChange = (targetUserKeys) => {
    this.setState({
      targetUserKeys,
    });
  };

  renderModalTable = () => {
    const {
      modalVisible,
      addType,
      checkedOrgKeys,
      checkedGroupKeys,
      targetUserKeys,
    } = this.state;
    const {
      form: { getFieldDecorator },
      currentRoleId,
    } = this.props;
    return (
      <Modal
        maskClosable={false}
        keyboard={false}
        style={{ minWidth: addType === "1" ? "920px" : "480px" }}
        destroyOnClose
        // title={addType === '1' ? '添加用户' : addType === '2' ? '添加用户组' : '添加组织'}
        title="修改成员分组"
        visible={modalVisible}
        onOk={this.okHandle}
        onCancel={this.handleModalVisible}
      >
        <Add
          addType={addType}
          // checkedOrgKeys={checkedOrgKeys}
          // onOrgTreeChcek={this.handleOrgTreeChcek}
          // checkedGroupKeys={checkedGroupKeys}
          // onGroupCheck={this.handleGroupCheck}
          targetUserKeys={targetUserKeys}
          onTargetChange={this.handleTargetKeysChange}
        />
      </Modal>
    );
  };

  renderAddMenu = () => {
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {this.memberTypeList.map((item, index) => {
          return (
            <Menu.Item key={++index}>
              <MyIcon className={styles.myIcon} type={item.iconType} />
              {item.render()}
            </Menu.Item>
          );
        })}
      </Menu>
    );
    return (
      <Dropdown overlay={menu} trigger={["click"]}>
        <button
          style={{
            backgroundColor: "#fff",
            border: "1px solid #ccc",
            borderRadius: "10%",
          }}
        >
          添加
        </button>
      </Dropdown>
    );
  };

  // 分页
  changePage = (page) => {
    this.setState({
      pageIndex: page,
    });
  };

  renderUsers = () => {
    const {
      form: { getFieldDecorator, getFieldValue },
      roleUserList,
      loadingRoleUserList,
      currentRoleId,
      deleteLoading,
      roleList,
    } = this.props;
    const { selectedRows, currentStatus } = this.state;

    return (
      <div className={styles.membersList}>
        <div style={{ marginBottom: 20 }}>
          {currentRoleId && this.renderAddMenu()}
          {selectedRows &&
            selectedRows.length > 0 && (
              <button
                loading={deleteLoading}
                onClick={this.deleteMembers}
                style={{
                  marginLeft: 10,
                  backgroundColor: "#fff",
                  border: "1px solid #ccc",
                  borderRadius: "10%",
                }}
              >
                删除
              </button>
            )}
        </div>
        <StandardTable
          showCheckbox
          rowKey="id"
          // pagination={false}
          selectedRows={selectedRows}
          loading={loadingRoleUserList}
          data={roleUserList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          // onChange={this.handleStandardTableChange}
          onChange={this.changePage}
        />
      </div>
    );
  };

  render() {
    console.log(this.props.editOrgTreeList);
    const { currentStatus } = this.state;
    const { updateRoleTreeLoading } = this.props;
    return (
      <div>
        <Tabs
          // defaultActiveKey={currentStatus}
          onChange={this.handleChangeTab}
          activeKey={this.state.activeKey}
        >
          <TabPane tab="角色成员" key={"1"}>
            {this.renderUsers()}
          </TabPane>
          <TabPane tab="角色权限" key={"2"}>
            <Row type="flex" justify="center">
              <Col span={20}>
                <Card className={styles.roleTree}>
                  <RoleTree
                    // onCheck={this.handleTreeCheck}
                    datatree={this.props.editOrgTreeList}
                    checkedKeys={this.props.checkedKeys}
                  />
                </Card>
              </Col>
            </Row>
            <Row type="flex" justify="center">
              <Col>
                <Button
                  loading={updateRoleTreeLoading}
                  type="primary"
                  onClick={this.updateTreeNode}
                >
                  确认提交
                </Button>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
        {this.renderModalTable()}
      </div>
    );
  }
}

export default Content;
